package com.atguigu.crowd.mvc.config;

import com.atguigu.crowd.constant.CrowdConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.authentication.configuration.EnableGlobalAuthentication;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Configuration          // 设置为配置类
@EnableWebSecurity      // 开启web环境下的权限控制功能
@EnableGlobalMethodSecurity(prePostEnabled = true)      // 启用全局方法控制权限功能
public class WebAppSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    @Override
    protected void configure(AuthenticationManagerBuilder builder) throws Exception {

        builder.userDetailsService(userDetailsService)
                .passwordEncoder(passwordEncoder);

    }
    @Override
    protected void configure(HttpSecurity security) throws Exception {

        // 整合所有需要放行的静态资源和需要放行的路径
        String[] permitUrls = {"/admin/to/login/page.html", "/index.jsp","/bootstrap/**","/crowdjscode/**",
                "/css/**", "/fonts/**", "/img/**", "/jquery/**", "/layer/**", "/script/**", "ztree/**"};

        security.authorizeRequests()                                     // 表示对请求进行授权
                .antMatchers(permitUrls)                                 // 传入ant风格的url
                .permitAll()                                             // 允许上面所有请求
                .antMatchers("/admin/get/page.html")
                .access("hasRole('经理') or hasAuthority('user:get')")
                .anyRequest()                                            // 其他未设置的全部请求
                .authenticated()                                         // 表示需要认证
                .and()
                .exceptionHandling()
                .accessDeniedHandler(new AccessDeniedHandler() {
                    @Override
                    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
                        httpServletRequest.setAttribute("exception", new Exception(CrowdConstant.MESSAGE_ACCESS_DENIED));
                        httpServletRequest.getRequestDispatcher("/WEB-INF/system-error.jsp").forward(httpServletRequest,httpServletResponse);
                    }
                })
                .and()
                .csrf()                                                  // 设置csrf
                .disable()                                               // 关闭csrf功能
                .formLogin()                                             // 开启表单登录功能
                .loginPage("/admin/to/login/page.html")                  // 指定登录页面
                .usernameParameter("loginAcct")                          // 设置表单中对应用户名的标签的name属性名
                .passwordParameter("userPswd")                           // 设置表单中对应密码的标签的name属性名
                .loginProcessingUrl("/security/do/login.html")           // 设置登录请求的提交地址
                .defaultSuccessUrl("/admin/to/main/page.html")           // 设置登录成功后去往的页面
                .and()
                .logout()                                                // 设置退出登录
                .logoutUrl("/security/do/logout.html")                   // 设置退出登录的请求
                .logoutSuccessUrl("/admin/to/login/page.html");          // 设置退出成功后前往的页面


    }
}
